package com.example.myspringai.util;

import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.record.Country;
import com.maxmind.geoip2.record.Location;
import com.maxmind.geoip2.record.Postal;
import com.maxmind.geoip2.record.Subdivision;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;

/**
 * @author st
 * Date:2021/2/1
 * Description
 **/
@Component
@Slf4j
public class IpAreaUtils {
    /**
     * ip库文件位置
     */
    @Value("${geoip2.dataFile:D:\\code\\deye-v6.2\\deye-search\\deye-search-web-v6.2.3\\search-web\\src\\main\\assembly\\geoip2\\ip.mmdb}")
    private String modelFileName;

    private static DatabaseReader reader;

    @PostConstruct
    public void init() {
        try {
            if (!System.getProperty("os.name").toLowerCase().contains("linux")) {
                modelFileName = "D:\\FlowerValleys\\deye-llm-research\\src\\main\\resources\\ip.mmdb";
            }
            // 读取离线库，根据文件存放位置自主修改
            File database = new File(modelFileName);
            reader = new DatabaseReader.Builder(database).build();
        } catch (IOException e) {
            log.error("初始加载ip库出错,错误信息:", e);
        }
    }

    /**
     * 根据ip获取国家,信息
     *
     * @param ip ip信息
     * @return
     */
    public static Map getCountryByIp(String ip, String lang) throws IOException, GeoIp2Exception {
        if (ip.trim().contains(" ")) {
            String[] ipLast = ip.trim().split(" ");
            ip = ipLast[ipLast.length - 1];
        }
        Map<String, Object> map = new HashMap<>(2 << 4);
        // 指定获取到的IP地址
        InetAddress ipAddress = InetAddress.getByName(ip);
        // 根据ip获取请求
        CityResponse response = reader.city(ipAddress);
        // 获取国家
        Country country = response.getCountry();
        Subdivision subdivision = response.getMostSpecificSubdivision();
        Postal postal = response.getPostal();
        Location location = response.getLocation();
        String zhCn = "zh-CN";
        map.putIfAbsent("iso-code", country.getIsoCode());
        map.putIfAbsent("subdivision-iso-code", subdivision.getIsoCode());
        map.putIfAbsent("postal", postal.getCode());
        map.putIfAbsent("longitude", location.getLongitude());
        map.putIfAbsent("latitude", location.getLatitude());
        if (lang.contains("fr")) {
            lang = "fr";
        }
        if (lang.contains("en")) {
            lang = "en";
        }
        if (lang.contains("zh")) {
            map.put("country", country.getNames().get(zhCn));
            map.putIfAbsent("subdivision", subdivision.getNames().get(zhCn));
            map.putIfAbsent("city", response.getCity().getNames().get(zhCn));
            if (StringUtils.isEmpty(response.getCity().getNames().get(zhCn))) {
                //  map.putIfAbsent("city", ((Map) (WxgzAddressApi.getPosition(location.getLongitude(), location.getLatitude(), null, null, null).get("data"))).get("areaname").toString());
                //  map.putIfAbsent("subdivision", ((Map) (WxgzAddressApi.getPosition(location.getLongitude(), location.getLatitude(), null, null, null).get("data"))).get("shortname").toString());
            }
        } else {
            map.put("country", country.getNames().get(lang));
            map.putIfAbsent("subdivision", subdivision.getNames().get(lang));
        }
        return map;
    }
}
